﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SHZY.Business.Entitys.Dto.VideoRecording;
using SHZY.Business.Entitys.Entity.VideoRecording;
using SHZY.Business.Interfaces.VideoRecording;
using SHZY.ClayObject;
using SHZY.Common.Configuration;
using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.Common.Enum;
using SHZY.Common.Filter;
using SHZY.Common.Models.NPOI;
using SHZY.Common.Security;
using SHZY.DataEncryption;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Entitys.Permission;
using SHZY.Systems.Interfaces.System;
using SqlSugar;

namespace SHZY.Business.VideoRecording
{
    /// <summary>
    /// 业务实现：摄像机Ip.
    /// </summary>
    [ApiDescriptionSettings(Tag = "system", Name = "QmsBaseCameraIp", Order = 200)]
    [Route("api/system/[controller]")]
    public class QmsBaseCameraIpService : IQmsBaseCameraIpService, IDynamicApiController, ITransient
    {
        /// <summary>
        /// 服务基础仓储.
        /// </summary>
        private readonly ISqlSugarRepository<QmsBaseCameraIpEntity> _repository;

        /// <summary>
        /// 多租户事务.
        /// </summary>
        private readonly ITenant _db;

        /// <summary>
        /// 数据接口服务.
        /// </summary>
        private readonly IDataInterfaceService _dataInterfaceService;

        /// <summary>
        /// 用户管理.
        /// </summary>
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="QmsBaseCameraIpService"/>类型的新实例.
        /// </summary>
        public QmsBaseCameraIpService(
            ISqlSugarRepository<QmsBaseCameraIpEntity> qmsBaseCameraIpRepository,
            IDataInterfaceService dataInterfaceService,
            ISqlSugarClient context,
            IUserManager userManager)
        {
            _repository = qmsBaseCameraIpRepository;
            _dataInterfaceService = dataInterfaceService;
            _db = context.AsTenant();
            _userManager = userManager;
        }

        /// <summary>
        /// 获取摄像机Ip.
        /// </summary>
        /// <param name="id">主键值.</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            return (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<QmsBaseCameraIpInfoOutput>();
        }

        /// <summary>
        /// 获取摄像机Ip列表.
        /// </summary>
        /// <param name="input">请求参数.</param>
        /// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] QmsBaseCameraIpListQueryInput input)
        {
            var data = await _repository.Context.Queryable<QmsBaseCameraIpEntity>().Where(w => w.DeleteMark == null)
                .WhereIF(!string.IsNullOrEmpty(input.ipAddress), it => it.IpAddress.Contains(input.ipAddress))
                .WhereIF(!string.IsNullOrEmpty(input.name), it => it.Name.Contains(input.name))
                .WhereIF(!string.IsNullOrEmpty(input.enabledMark), it => it.EnabledMark == Convert.ToInt32(input.enabledMark))
                .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.IpAddress.Contains(input.keyword) || it.Name.Contains(input.keyword) || it.EnabledMark == Convert.ToInt32(input.enabledMark))
                .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.Id)
                .Select(it => new QmsBaseCameraIpListOutput
                {
                    id = it.Id,
                    ipAddress = it.IpAddress,
                    name = it.Name,
                    remark = it.Remark,
                    creatorUserId = it.CreatorUserId,
                    creatorTime = it.CreatorTime,
                    enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "禁用", "正常"),
                }).OrderByIF(!string.IsNullOrEmpty(input.sidx), it => input.sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
            return PageResult<QmsBaseCameraIpListOutput>.SqlSugarPageResult(data);
        }

        /// <summary>
        /// 新建摄像机Ip.
        /// </summary>
        /// <param name="input">参数.</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] QmsBaseCameraIpCrInput input)
        {
            var entity = input.Adapt<QmsBaseCameraIpEntity>();
            entity.Id = SnowflakeIdHelper.NextId();
            var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
            if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1000);
        }

        /// <summary>
        /// 获取摄像机Ip无分页列表.
        /// </summary>
        /// <param name="input">请求参数.</param>
        /// <returns></returns>
        private async Task<dynamic> GetNoPagingList([FromQuery] QmsBaseCameraIpListQueryInput input)
        {
            return await _repository.Context.Queryable<QmsBaseCameraIpEntity>().Where(w => w.DeleteMark == null)
                .WhereIF(!string.IsNullOrEmpty(input.ipAddress), it => it.IpAddress.Contains(input.ipAddress))
                .WhereIF(!string.IsNullOrEmpty(input.name), it => it.Name.Contains(input.name))
                .WhereIF(!string.IsNullOrEmpty(input.enabledMark), it => it.EnabledMark == Convert.ToInt32(input.enabledMark))
                .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.IpAddress.Contains(input.keyword) || it.Name.Contains(input.keyword) || it.EnabledMark == Convert.ToInt32(input.enabledMark))
                .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.Id)
                .Select(it => new QmsBaseCameraIpListOutput
                {
                    id = it.Id,
                    ipAddress = it.IpAddress,
                    name = it.Name,
                    remark = it.Remark,
                    creatorUserId = it.CreatorUserId,
                    creatorTime = it.CreatorTime,
                    enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "禁用", "正常"),
                }).OrderByIF(!string.IsNullOrEmpty(input.sidx), it => input.sidx + " " + input.sort).ToListAsync();
        }

        /// <summary>
        /// 导出摄像机Ip.
        /// </summary>
        /// <param name="input">请求参数.</param>
        /// <returns></returns>
        [HttpGet("Actions/Export")]
        public async Task<dynamic> Export([FromQuery] QmsBaseCameraIpListQueryInput input)
        {
            var exportData = new List<QmsBaseCameraIpListOutput>();
            if (input.dataType == 0)
                exportData = Clay.Object(await GetList(input)).Solidify<PageResult<QmsBaseCameraIpListOutput>>().list;
            else
                exportData = await GetNoPagingList(input);
            List<ParamsModel> paramList = "[{\"value\":\"IP 地址\",\"field\":\"ipAddress\"},{\"value\":\"有效标志\",\"field\":\"enabledMark\"},{\"value\":\"创建人\",\"field\":\"creatorUserId\"},{\"value\":\"创建时间\",\"field\":\"creatorTime\"},{\"value\":\"名称\",\"field\":\"name\"},{\"value\":\"备注\",\"field\":\"remark\"},]".ToList<ParamsModel>();
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.FileName = "摄像机Ip.xls";
            excelconfig.HeadFont = "微软雅黑";
            excelconfig.HeadPoint = 10;
            excelconfig.IsAllSizeColumn = true;
            excelconfig.ColumnModel = new List<ExcelColumnModel>();
            foreach (var item in input.selectKey.Split(',').ToList())
            {
                var isExist = paramList.Find(p => p.field == item);
                if (isExist != null)
                    excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
            }

            var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
            ExcelExportHelper<QmsBaseCameraIpListOutput>.Export(exportData, excelconfig, addPath);
            var fileName = _userManager.UserId + "|" + addPath + "|xls";
            return new
            {
                name = excelconfig.FileName,
                url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "SHZY")
            };
        }

        /// <summary>
        /// 批量删除摄像机Ip.
        /// </summary>
        /// <param name="ids">主键数组.</param>
        /// <returns></returns>
        [HttpPost("batchRemove")]
        public async Task BatchRemove([FromBody] List<string> ids)
        {
            var entitys = await _repository.Context.Queryable<QmsBaseCameraIpEntity>().In(it => it.Id, ids).ToListAsync();
            if (entitys.Count > 0)
            {
                var AnyLineIp = await _repository.Context.Queryable<QmsBaseCameraIpEntity, QmsBaseCameraLineIpEntity>((it, ie) => new JoinQueryInfos(JoinType.Right, it.IpAddress == ie.IpAddress))
                              .Where((it, ie) => it.DeleteMark == null && ie.DeleteMark == null && ids.Contains(it.Id)).AnyAsync();
                if (AnyLineIp)
                {
                    throw Oops.Oh("所选IP已维护产线,无法删除!");
                }
                try
                {

                    // 开启事务
                    _db.BeginTran();
                    // 批量删除摄像机Ip
                    var isOk = await _repository.Context.Updateable<QmsBaseCameraIpEntity>().SetColumns(it => new QmsBaseCameraIpEntity()
                    {
                        DeleteTime = DateTime.Now,
                        DeleteMark = 1,
                        DeleteUserId = _userManager.UserId
                    }).Where(it => ids.Contains(it.Id)).ExecuteCommandHasChangeAsync();

                    // 关闭事务
                    _db.CommitTran();
                }
                catch (Exception)
                {
                    // 回滚事务
                    _db.RollbackTran();

                    throw Oops.Oh(ErrorCode.COM1002);
                }
            }
        }

        /// <summary>
        /// 更新摄像机Ip.
        /// </summary>
        /// <param name="id">主键值.</param>
        /// <param name="input">参数.</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] QmsBaseCameraIpUpInput input)
        {
            var entity = input.Adapt<QmsBaseCameraIpEntity>();
            var isOk = await _repository.Context.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).CallEntityMethod(m => m.LastModify()).ExecuteCommandAsync();
            if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1001);
        }

        /// <summary>
        /// 删除摄像机Ip.
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var AnyLineIp = await _repository.Context.Queryable<QmsBaseCameraIpEntity, QmsBaseCameraLineIpEntity>((it, ie) => new JoinQueryInfos(JoinType.Right, it.IpAddress == ie.IpAddress))
             .Where((it, ie) => it.DeleteMark == null && ie.DeleteMark == null && it.Id == id).AnyAsync();
            if (AnyLineIp)
            {
                throw Oops.Oh("当前IP已维护产线,无法删除!");
            }

            var isOk = await _repository.Context.Updateable<QmsBaseCameraIpEntity>().SetColumns(it => new QmsBaseCameraIpEntity()
            {
                DeleteTime = DateTime.Now,
                DeleteMark = 1,
                DeleteUserId = _userManager.UserId
            }).Where(x => x.Id == id).ExecuteCommandHasChangeAsync();
            if (!isOk)
                throw Oops.Oh(ErrorCode.COM1002);
        }
    }
}
